package cn.calm.xhtml.impl.fun;

import java.util.Collection;

import cn.calm.xhtml.annotation.Attribute;
import cn.calm.xhtml.annotation.Tag;
import cn.calm.xhtml.api.exception.XhtmlException;
import cn.calm.xhtml.api.service.AbstraceNodeProcess;
import cn.calm.xhtml.api.service.Status;
import cn.calm.xhtml.api.service.Statusable;
import cn.calm.xhtml.api.service.XhtmlContext;

@Tag(namespace = "http://www.calm.cn/xhtml/extras/core", attributes = {
		@Attribute(name = "value", description = "迭代对象", template = "<label></label><input name=\"value\"/>"),
		@Attribute(name = "var", description = "当前对象", template = "<label></label><input name=\"var\"/>"),
		@Attribute(name = "status", description = "当前状态", template = "<label></label><input name=\"status\"/>") })
public class Each extends AbstraceNodeProcess implements Statusable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String var;
	private String status;

	@Override
	public void processNode(XhtmlContext context) throws XhtmlException {
		Object value = getAttrValue("value", context);
		var = getAttr("var");
		if (value == null) {
			return;
		}
		status = getAttr("status");
		if (status == null) {
			status = STATUS_DEFAULT;
		}
		Collection<?> ite = convertCollection(value);
		int index = 0;
		for (Object o : ite) {
			context.setValue(var, o);
			context.setValue("${" + status + "}", new Status(index++, o));
			processChildren(context);
		}
		context.removeValue(var);
		context.removeValue(status);
	}

	@Override
	public String getStatus() {
		return status;
	}

}
